<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

class schoolCon extends rootCon{
    public function adminStatusAction()  {//the status of the school
        $uid = mylogin::getUid(true);
        $schoolAdmin = new SchoolAdmin();
        $find = $schoolAdmin->find(['uid'=>$uid]);
        if(!$find || $schoolAdmin->status != STATUS_PUBLISH){
            $status = $schoolAdmin->status;
            if(!$find) $status = 7;
            $this->j(0,"",['status'=>$status]);
        }

        $school = new School();
        $school->find($schoolAdmin->schoolId);
        if($school->validDate<date('Y-m-d H:i:s')){
            $school->status = 2;//已经过期
        }

        $this->j(0,"",['status'=>$school->status,'schoolId'=>$school->schoolId]);
    }

    //机构主页端老师
    public function teacherListAction(){
        $uid = mylogin::getUid(false);
        $schoolId = r_int('schoolId');

        $teacherSchool = new SchoolTeacher();
        $sql = "SELECT t.teacherId,t.teacherName,t.finalScore,t.summary,t.uploadImg  FROM tbl_teacher t  LEFT JOIN ".$teacherSchool->table()." ts ON ts.teacherId=t.teacherId WHERE ts.schoolId=$schoolId AND t.status=".STATUS_PUBLISH." AND ts.status=".STATUS_PUBLISH;

      /*  $teacher = new Teacher();
        $teacher->schoolId = $schoolId;
        $teacher->status = STATUS_PUBLISH;
        $con = $teacher->getConByLoad();
        $sql = "SELECT teacherId,teacherName,finalScore,summary,uploadImg  FROM ".$teacher->table()." WHERE ".$con." AND teacherName IS NOT NULL ORDER BY ".$teacher->key()." DESC";*/
        $rect = $teacherSchool->pager($sql);
/*$i        $i = 0;
        foreach($rect['list'] as $item){
            $courseId = $item['courseId'];
            $courseImage = new CourseImage();
            $courseImage->courseId = $courseId;
            $courseImage->status = STATUS_PUBLISH;
            $all = $courseImage->findAll();
            $rect['list'][$i]['courseImage'] = $all;
            $i++;
        }*/

        
        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->schoolId = $schoolId;
        $schoolAdmin->uid = $uid;
        $findAdmin = $schoolAdmin->find();
        if(!$findAdmin) Traceext::log($uid,"老师列表","老师列表",$schoolId);
        
        $this->j(0,'',$rect);
    }

    //附近的机构
    public function nearAction(){
        $uid = mylogin::getUid(true);
        $schoolId = r_int('schoolId');
        $schoolObj = new School();
        $schoolObj->find($schoolId);

        $orderBy = mygeo::getOrderBy($schoolObj->lat,$schoolObj->lng);

        $sql = "SELECT schoolId FROM ".$schoolObj->table()." WHERE status=".STATUS_PUBLISH." ORDER BY $orderBy LIMIT 5";
        $result = $schoolObj->query($sql);
        $rect = [];
        for($i = 0; $i < count($result); $i++){
            $schoolId = $result[$i]['schoolId'];
            $rect[] = $this->getSchoolInfo($schoolId,$uid);
        }

        $this->j(0,"",$rect);
    }

    //机构主页端课程
    public function courseListAction(){
        $uid = mylogin::getUid(true);
        $schoolId = r_int('schoolId');
        $course = new Course();
        $course->schoolId = $schoolId;
        $course->status = STATUS_PUBLISH;
        $con = $course->getConByLoad();
        $sql = "SELECT courseId,courseName,price,oldPrice,totalClassHours,uploadImg  FROM ".$course->table()." WHERE ".$con." ORDER BY ".$course->key()." DESC";
        $rect = $course->pager($sql);
        $i = 0;
        foreach($rect['list'] as $item){
            $courseId = $item['courseId'];
            $courseImage = new CourseImage();
            $courseImage->courseId = $courseId;
            $courseImage->status = STATUS_PUBLISH;
            $all = $courseImage->findAll();
            $rect['list'][$i]['courseImage'] = $all;
            $i++;
        }

        $teacher = new Teacher();
        $teacher->uid = $uid;
        $teacher->find();
        $schoolTeacher = new SchoolTeacher();
        $schoolTeacher->schoolId  = $schoolId;
        $schoolTeacher->teacherId = $teacher->teacherId;
        $findTeacher = $schoolTeacher->find();
        
        if(!$findTeacher){
            $schoolAdmin = new SchoolAdmin();
            $schoolAdmin->schoolId = $schoolId;
            $schoolAdmin->uid = $uid;
            $findAdmin = $schoolAdmin->find();
            if(!$findAdmin) Traceext::log($uid,"课程列表","课程列表",$schoolId);
        }


        $this->j(0,'',$rect);
    }

    //学校累计值统计信息
    public function totalAction(){
        $uid = mylogin::getUid(false);
        $schoolId = r_int('schoolId');
        if(!$schoolId) $this->j(-1,"缺少学校ID参数",['schoolId'=>$schoolId]);

        $schoolObj = new School();
        $schoolObj->find($schoolId);
        $schoolObj->hide();
        $rect = $schoolObj->arr;
        $rect['renqizhi']    = $schoolObj->likeCount;
        $rect['remarkCount'] = $schoolObj->scoreCount;//评分数量


        $course = new Course();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$course->table()." WHERE schoolId=".$schoolId." AND status=".STATUS_PUBLISH;
        $one = $course->one($sql);
        $rect['courseCount'] = intval($one['NUM']);

        //学过的人统计
        $schoolLearned = new SchoolLearned();
        $schoolLearned->schoolId = $schoolId;
        $sql = "SELECT COUNT(1) AS NUM FROM ".$schoolLearned->table()." WHERE ".$schoolLearned->getConByLoad();
        $one = $schoolLearned->one($sql);
        
        $rect['learned'] = $one['NUM'];
        if($schoolObj->learned != $one['NUM']){
            $schoolObj->learned = $one['NUM'];
            if($schoolObj->schoolId) $schoolObj->save();
        }

        $schoolTypeObj = new SchoolType();
        $schoolTypeObj->find($schoolObj->schoolTypeId);

        $typeObj2 = new SchoolType2();
        $typeObj2->find($schoolObj->typeId2);
        $rect['tag'] = "{$schoolTypeObj->typeName}-{$typeObj2->typeName}";

        $this->j(0,"机构管理首页",$rect);
    }


    public function statusAction(){
        $uid = mylogin::getUid(true);

        $schoolAdmin = new SchoolAdmin();//这里现在只支持一个学校
        $schoolAdmin->find([['uid'=>$uid],['status'=>STATUS_PUBLISH]]);
        $data['schoolId'] = $schoolAdmin->schoolId;//已经通过审核的学校id
        $schoolId = $data['schoolId'];

        //这里只显示一个学校,访客数
        $today = date('Y-m-d');
        $sqlVisite = "SELECT uid FROM tbl_visitor WHERE schoolId=".$schoolId." AND created LIKE '$today%' GROUP BY uid";
        $result = $schoolAdmin->query($sqlVisite);
        $data['visitCount']    = count($result);
        $info = '';
        if(IS_DEBUG) $info=$sqlVisite;

        //预约人数
        $data['dateCount']     = Traceext::getDailyAppBySchool($schoolId);


        $schoolAdmin = new SchoolAdmin();
        $sql = "SELECT schoolId  FROM ".$schoolAdmin->table()." WHERE uid=$uid AND status!=".STATUS_ADMIN_DELETE." ORDER BY ".$schoolAdmin->key()." DESC ";//从tbl_school管理端添加addFrom=2
        $all = $schoolAdmin->query($sql);
        $data['schoolCount']   = count($all);//访问人数
        $schoolIds = [-1];
        foreach($all as $item){
            $schoolIds[] = $item['schoolId'];
        }
        if(!$data['schoolId']) $data['schoolId'] = $all[0]['schoolId'];//若没有通过审核的学校默认显示最新的学校


        //机构课程数量
        $course = new Course();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$course->table()." WHERE schoolId IN (".join(",",$schoolIds).") AND status IN (0,3,5)";
        $one = $course->one($sql);
        $data['courseCount']   = intval($one['NUM']);//
        
        

        //上课人数
        $courseApp = new CourseAppointment();
        $date = date('Y-m-d');
        $sql = "SELECT COUNT(1) AS NUM FROM ".$courseApp->table()." WHERE schoolId IN (".join(",",$schoolIds).") AND status IN (3,4,7) AND `date`='{$date}'";//以经支付的课程
        $one = $courseApp->one($sql);
        $data['classCount']    = intval($one['NUM']);//
        


        //---老师的数量---
        $schoolTeacher = new SchoolTeacher();
        $sql = "SELECT COUNT(1) AS NUM FROM ".$schoolTeacher->table()." st LEFT JOIN tbl_teacher t ON st.teacherId=t.teacherId WHERE st.schoolId IN (".join(",",$schoolIds).") AND st.status IN (0,3) AND t.status!=88";
        $one = $schoolTeacher->one($sql);
        $data['teacherCount']  = intval($one['NUM']);//
        

        $this->j(0,$info,$data);
    }

    public function summaryAction(){
        $uid = mylogin::getUid(true);
        $month = r('month');
        if(!$month){
            $this->j(-1,'缺少参数',['monty'=>$month]);
        }

        $school  = new School();;
        $school->load();
        $con = "created LIKE '$month%' AND uid=".$uid;

        if(s('status')){
            $con .= " AND status=".r_int('status');
        }

        $all = $school->all($con);
        $this->j(0,'',$all);
    }
	
	/**
	 * 品牌管理
	 */
    public function brandAction(){
        $list = myredis::getArray("schoolBrand");
        if($list){
            $this->j(0, "cache",$list);
        }

        $obj = new SchoolBrand();
        $all = $obj->all(['status',STATUS_PUBLISH]);
        myredis::setArray("schoolBrand",$all,600);
        $this->j(0,'db',$all);
    }


    public function infoAction(){
        $uid = mylogin::getUid(false);
        $info = r('schoolId');
        if(is_array($info)){
            $list = [];
            $i = 0;
            foreach($info as $schoolId){
                if($i>6) break;
                $schoolId = intval($schoolId);

                $one = $this->getSchoolInfo($schoolId,$uid);
                if($schoolId && $one)   $list[] = $one;
                $i++;
            }
            $this->j(0,'列表',$list);
        }else{//单个学校
            $schoolId = r_int('schoolId');
            $info = $this->getSchoolInfo($schoolId,$uid);

            if(r('isAdmin')){
                $schoolAdmin = new SchoolAdmin();
                $schoolAdmin->schoolId = $schoolId;
                $schoolAdmin->uid = $uid;
                $schoolAdmin->status = STATUS_PUBLISH;
                $isSchoolAdmin  = $schoolAdmin->find();
                if($isSchoolAdmin){
                    $course = new Course();
                    $sql = "SELECT COUNT(1) AS NUM FROM ".$course->table()." WHERE schoolId=".$schoolId;
                    $one = $course->getOne($sql);
                    $info['courseCount'] = $one['NUM'];

                    $schoolTeacher = new SchoolTeacher();
                    $sql = "SELECT COUNT(1) AS NUM FROM  ".$schoolTeacher->table()." WHERE schoolId=".$schoolId;
                    $one = $schoolTeacher->getOne($sql);
                    $info['teacherCount'] = $one['NUM'];


                }else{
                    $info['courseCount'] = "您不是当前学校的管理员";
                }
            }else{
                $schoolAdmin = new SchoolAdmin();
                $schoolAdmin->schoolId = $schoolId;
                $schoolAdmin->uid = $uid;
                $schoolAdmin->status = STATUS_PUBLISH;
                $isSchoolAdmin  = $schoolAdmin->find();
                if(!$isSchoolAdmin){
                    Traceext::log($uid,"查看主页","主页",$schoolId);
                }
            }

/*            $remark = new RemarkSchool();
            $sql = "SELECT * FROM ".$remark->table()." WHERE status=".STATUS_PUBLISH." AND schoolId=".$schoolId;
            $remarkList = $remark->pager($sql);
            $info['remark'] = $remarkList;*/
            $schoolTeacher = new SchoolTeacher();
            $sql = "SELECT  st.teacherId,t.teacherName,t.uploadImg,t.years,t.teacherYear,t.likeCount,t.finalScore  FROM ".$schoolTeacher->table()." st LEFT JOIN tbl_teacher t ON st.teacherId=t.teacherId  WHERE t.status=3 AND  st.schoolId=".$schoolId;
            $allTeacher = $schoolTeacher->query($sql);//teacherName和uploadImg
            $i = 0;
            foreach($allTeacher as $item){
                $teacherLabelObj = new TeacherLabel();
                $labels = $teacherLabelObj->all(['teacherId'=>$item['teacherId'],'status'=>STATUS_PUBLISH]);
                $allTeacher[$i]['teacherLabel'] = $labels;
                if(is_numeric($allTeacher[$i]['teacherYear'])){
                    $allTeacher[$i]['teacherYear'] = $allTeacher[$i]['teacherYear']."年教龄";
                }
                $i++;
            }


            $info['allTeacher'] = $allTeacher;
            $this->j(0,'单个',$info);
        }
    }

    private function getSchoolInfo($schoolId,$uid) {
        $obj = new School();
        $objId = intval($schoolId);
        $statusSubmit = "";
        if(r('isAdmin')) $statusSubmit = " OR status=".STATUS_SUBMIT;
        $con = $obj->key()."=".$objId." AND (uid=$uid OR status=".STATUS_PUBLISH."  $statusSubmit)";

        $find = $obj->find($con);

        if(!$find){
            return false;
        }

        $obj->hide();

        //图片
        $schoolImage = new SchoolImage();
        $schoolImage->schoolId = $objId;
        $allSchoolImage = $schoolImage->all("schoolId=".$objId);
        $obj->arr['schoolImages'] = $allSchoolImage;

        //机构标签
        $schoolTag = new SchoolTag();
        $all = $schoolTag->all("schoolId=".$objId." AND status=".STATUS_PUBLISH);
        $obj->arr['schoolTags'] = $all;

        //审核日志
        if($obj->uid==$uid){
            $schoolLog = new SchoolReason();
            $schoolLog->schoolId = $objId;
            $all = $schoolLog->all($schoolLog->getConByLoad());
            $obj->arr['schoolReason'] = $all;
        }else{
            $obj->arr['schoolReason'] = [];
        }

        //关注
        $schoolFeed = new SchoolFeed();
        $schoolFeed->schoolId = $schoolId;
        $schoolFeed->uid = $uid;
        $focus = $schoolFeed->find();
        $obj->arr['focus'] = $focus;
        $obj->arr['learnedCount'] = $obj->arr['learned'];
        $obj->arr['learned'] = $this->getSchoolLearned($objId);

        $startLat = s('lat')?r('lat'):-1;
        $startLng = s('lng')?r('lng'):-1;

        if($startLat==-1 || $startLng==-1){
            $user = new User();
            $user->find($uid);
            $startLat = $user->lat;
            $startLng = $user->lng;
        }

        $distance = mygeo::getDistanceAuto($startLat,$startLng,$obj->lat,$obj->lng);
        $obj->arr['distance'] = $distance;

        $schoolWantObj = new SchoolWant();
        $schoolWantObj->schoolId = $schoolId;
        $schoolWantObj->uid = $uid;
        $find = $schoolWantObj->find();
        $obj->arr['iWant'] = $find;


        $schoolLike = new SchoolLike();
        $schoolLike->schoolId = $schoolId;
        $schoolLike->uid = $uid;
        $find = $schoolLike->find();
        $obj->arr['iLike'] = $find;

        return $obj->arr;
    }


    //点赞
    public function likeAction(){
        $uid = mylogin::getUid(true);
        $obj = new SchoolLike();
        $obj->load();
        $schoolId = $obj->schoolId;
        $obj->uid = $uid;
        $find = $obj->find();

        //删除@todo 修改为状态模式,避免刷积分
        if($find){
            $sql = "DELETE FROM ".$obj->table()." WHERE schoolId=".$schoolId." AND uid=".$uid;
            $obj->query($sql);
        }else{ //保存
            $user = new User();
            $user->find($uid);

            $obj->avatar = $user->avatar;
            $obj->uid = $uid;
            $obj->ip = myrequest::getIP();
            $obj->created = date('Y-m-d H:i:s');
            $obj->save();

            $user->sendLike = $user->sendLike+1;
            $user->save();

            $school = new School();
            $school->find($schoolId);
            $urlDesc = $school->schoolName;
            $url = "pages/schooldetail/index?schoolId=$schoolId";
            $img = $school->logoUrl;
            ScoreExt::add($uid,1,5,"喜欢",$urlDesc,$url,$img);
        }

        //统计
        $sql = "SELECT COUNT(1) AS NUM FROM ".$obj->table()." WHERE schoolId=".$schoolId;
        $one = $obj->one($sql);
        $likeCount = $one['NUM'];

        //update
//        $obj = new School();
//        $obj->likeCount = $likeCount;
//        $con = ['schoolId',$schoolId];
//        $obj->save($con);

        $this->j(0,'',['likeCount'=>$likeCount]);
    }

    public function saveAction() {
        $uid = mylogin::getUid(false);
        $obj = new School();

        $objId = r_int($obj->key());
        if($objId){
            $find = $obj->find([[$obj->key(),$objId],['uid',$uid]]);
            if(!$find){
                $this->j(-1,'没有找到对应的信息',[$obj->key()=>$objId]);
            }
        }
        $obj->load();
        if(!$objId){//新增
            $obj->validDate = date('Y-m-d H:i:s',time()+3600*24*15);
        }


        if(s('lng')) $obj->lng = number_format(r('lng'), 7, '.', '');
        if(s('lat')) $obj->lat = number_format(r('lat'), 7, '.', '');
        if(s('lng')) $obj->geo = mygeo::getHash($obj->lat,$obj->lng);

        if($obj->cityId){
            //省份id
            $obj->province = $obj->cityId[0];
            $provinceName = $obj->province;
            $provinceObj = new Province();
            $provinceObj->provinceName = $provinceName;
            if($find) $provinceObj->find();
            if($find) $obj->provinceId = $provinceObj->provinceId;

            //城市id
            $cityName          = $obj->cityId[1];
            $city = new City();
            $city->cityName = $cityName;
            $city->provinceId = $obj->provinceId;
            $find = $city->find();
            if($find) $obj->cityIdOk = $city->cityIdOk;

            //区id
            $obj->district = $obj->cityId[2];
            $districtObj = new District();
            $districtObj->provinceId = $obj->provinceId;
            $districtObj->cityIdOk = $obj->cityIdOk;
            $districtObj->districtName = $obj->district;
            $districtObj->districtName = mb_ereg_replace ("新区","",$districtObj->districtName);
            $districtObj->districtName = mb_ereg_replace ("区","",$districtObj->districtName);
            $find = $districtObj->find();
            if($find) $obj->districtId = $districtObj->districtId;
        }




        $imgId = r_int('logo');
        if($imgId){
            $img = new ImageFile();
            $find = $img->find($imgId);
            $obj->logoUrl = $img->uploadImg;
        }

        $obj->uid = $uid;
        $obj->ip  = myrequest::getIP();
        $obj->created = date('Y-m-d H:i:s');
        if($obj->status != STATUS_PUBLISH && !s('status'))  $obj->status = STATUS_SUBMIT;
        if(!$obj->schoolId)  $obj->status = STATUS_SUBMIT;//首次添加默认为待审核

        if(r('isAdmin')){
            if(!$obj->schoolId) $obj->addFrom = 2;//是机构管理员添加的为2，推广员添加的为1
        }
        
        if(!$obj->schoolId) {
        	$obj->likeCount = rand(99, 999);
        	$obj->want = rand(99, 999);
            $obj->scoreCount = rand(99, 999);
        }
        $obj->save();

        //记录图片id和机构id的关联关系到tbl_school_image表中
        $this->saveSchoolImage($obj->schoolId);
        $this->saveSchoolTag($obj->schoolId);


        $obj->hide();

        $rect = $obj->arr;

        $rect['geoUpdate'] = false;
        if(s('lng') && s('lat')){
            //更新所有的课程和教师
            $geoSql = "lng=".$obj->lng.",lat=".$obj->lat.",geo='".$obj->geo."'";
            $sql = "UPDATE tbl_teacher SET $geoSql WHERE schoolId=".$obj->schoolId;
            $obj->query($sql);

            //更新所有的课程和教师
            $sql = "UPDATE tbl_course SET $geoSql WHERE schoolId=".$obj->schoolId;
            $obj->query($sql);
            $rect['geoUpdate'] = true;
        }

        //记录机构管理员
        if(r('isAdmin')){
            $schoolAdmin = new SchoolAdmin();
            $schoolAdmin->uid = $uid;
            $schoolAdmin->schoolId = $obj->schoolId;
            $find = $schoolAdmin->find();
            if(!$find){
                $schoolAdmin->save();
            }
        }

        $this->j(0,'保存成功',$rect);
    }

    private function saveSchoolTag($schoolId){
        if(!s('schoolTags')) return;
        $allImg = r('schoolTags');
        //删除之前的
        $schoolTag = new SchoolTag();
        $sql = "DELETE FROM ".$schoolTag->table()." WHERE schoolId=".$schoolId;
        $schoolTag->query($sql);

        if(!is_array($allImg)) $allImg =[$allImg];
        $i = 0;
        foreach($allImg as $tmpObj){
            $i++;
            if(!$tmpObj) continue;
            $img = new Tag();
            $find = $img->find($tmpObj->tagId);
            if(!$find) continue;

            $schoolTag = new SchoolTag();
            $schoolTag->schoolId = $schoolId;
            $schoolTag->tagId = $img->tagId;
            $schoolTag->tagName = $img->tagName;
            $schoolTag->status = STATUS_PUBLISH;//自己人不用审核
            $schoolTag->save();
        }
    }

    private function saveSchoolImage($schoolId){
        if(!s('schoolImages')) return;

        $allImg = r('schoolImages');
        //删除之前的
        $schoolImage = new SchoolImage();
        $sql = "DELETE FROM ".$schoolImage->table()." WHERE schoolId=".$schoolId;
        $schoolImage->query($sql);

        if(!is_array($allImg)) $allImg =[$allImg];
        $i = 0;
        foreach($allImg as $imgId){
            $i++;

            if(!$imgId) continue;

            $img = new ImageFile();
            $find = $img->find($imgId);

            $schoolImage = new SchoolImage();
            $schoolImage->schoolId = $schoolId;
            $schoolImage->imageFileId = $imgId;
            $schoolImage->img = $img->uploadImg;
            $schoolImage->sort = $i;
            $schoolImage->status = STATUS_PUBLISH;//自己人不用审核
            $schoolImage->save();
        }
    }

    //全部的
    public function allAction(){
        $uid = mylogin::getUid(true);

        $lat = mygeo::getLat($uid);
        $lng = mygeo::getLng($uid);


        $obj = new School();
        $obj->load();
        $obj->status = STATUS_PUBLISH;
        $con = $obj->getConByLoad();
        if(r('keyword')){
            $key = addslashes(trim(r('keyword')));
            //$con .= " AND (schoolName LIKE '%$key%' OR summary LIKE '%$key%') ";
            $con .= " AND schoolName LIKE '%$key%'  ";
        }

        $sql = "SELECT * FROM ".$obj->table()." WHERE ".$con;
        switch(r('orderBy')){
            case "effect":
                $order = " effectScore DESC";
                break;
            case "service":
                $order = " serviceScore DESC";
                break;
            case "remark":
            $order = " finalScore DESC";
                break;
            case "distance"://zhaopeixunapi.hkbao.com/school,all?orderBy=distance&lat=39.908491&lng=116.374328
            default:
                $order = mygeo::getOrderBy();
        }


        $obj->autoHide = false;
        $all = $obj->pager($sql,20,$order);

        $startLat = s('lat')?r('lat'):-1;
        $startLng = s('lng')?r('lng'):-1;

        if($startLat==-1 || $startLng==-1){
            $user = new User();
            $user->find($uid);
            $startLat = $user->lat;
            $startLng = $user->lng;
        }

        $i = 0;
        foreach($all['list'] as $item){
            $distance = mygeo::getDistanceAuto($startLat,$startLng,$item['lat'],$item['lng']);
            $all['list'][$i] = $obj->hide($item);
            $all['list'][$i]['distance'] = $distance;
            $all['list'][$i]['logoUrl'] = $this->getSmallImg($item['logoUrl']);
            $i++;
        }

        $all['city'] = mygeo::getCity();
        $all['district'] = mygeo::getDistrictByCity($all['city'] );

        $this->j(0, "list",$all);
    }

    private function getSmallImg($img){
        //https://img.myclhc.com/images/03aeba9e71501863aa70c6fe9c1da145.jpg
        //https://img.myclhc.com/images/90/03aeba9e71501863aa70c6fe9c1da145.jpg
        return preg_replace("/images\//","images/90/",$img);
    }

    //推广员或者机构管理员学校列表
    public function listAction() {
        $uid = mylogin::getUid(true);
        $obj = new School();
        $obj->load();
        $obj->uid = $uid;

        if(r('isAdmin')){
            $obj->addFrom = 2;//管理端上传
        }else{
            $obj->addFrom = 1;//推广员上传
        }

        $con = $obj->getConByLoad();
        $con .= " AND status!=88 ";

        $all = $obj->all($con);



        $i = 0;
        foreach($all as $item){
            //$all[$i]['distance'] = "1KM";///@todo
            //课程和老师数量
            $schoolId = $item['schoolId'];
            $sql = "SELECT COUNT(1) AS NUM FROM tbl_course WHERE status IN (3,0,4) AND schoolId=".$schoolId;
            $course = new Course();
            $one = $course->one($sql);
            $all[$i]['courseCount'] = intval($one['NUM']);

            $schoolTeacher = new SchoolTeacher();
            $sql = "SELECT teacherId  FROM ".$schoolTeacher->table()." WHERE status IN (3,0,4) AND schoolId=".$schoolId;
            $allTeacherId = $schoolTeacher->query($sql);
            $teacherIdArr = [-1];
            foreach($allTeacherId as $item){
                $teacherIdArr[] = $item['teacherId'];
            }


            $teacherIdStr = join($teacherIdArr,",");
            $sql = "SELECT COUNT(1) AS NUM FROM tbl_teacher WHERE status IN (3,0,4) AND teacherId IN ($teacherIdStr)";
            $one = $schoolTeacher->one($sql);
            $all[$i]['teacherCount'] = intval($one['NUM']);
            $all[$i]['teacherCountSql'] = $sql;

            $i++;
        }

        $this->j(0, "list",$all);
    }

    public function typeAction(){
        $obj = new SchoolType();
        $result = $obj->all(['status'=>3]);

        $i = 0;
        foreach($result as $item){
            $mainId = $item['schoolTypeId'];
            $type2 = new SchoolType2();
            $subAll = $type2->all(['schoolTypeId',$mainId]);
            $result[$i]['subType'] = $subAll;
            $i++;
        }

        $this->j(0, "机构类别",$result);
    }



    //想学
    public function wantAction(){
        $uid = mylogin::getUid(true);
        $school = new School();
        $objId = r_int($school->key());
        $find = $school->find($objId);
        if(!$find) $this->j(-1,"参数错误",[$school->key()=>$objId]);

        $obj = new SchoolWant();
        $obj->uid = $uid;
        $obj->schoolId= $objId;
        $find = $obj->find();
        if($find){//cancel
            /*$sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND schoolId=$objId";
            $obj->query($sql);
            $school->want = $school->want-1;
            $school->save();*/
        }else{
            $obj->save();
            $school->want = $school->want+1 ;
            $school->save();
        }
        $this->j(0,"",['want'=>$school->want]);
    }

    //想学的人列表
    public function wantListAction(){
        $uid = mylogin::getUid(true);

        //当前的老师
        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->uid = $uid;
        $schoolAdmin->status = STATUS_PUBLISH;
        $schoolAdmin->find();

        $obj = new SchoolWant();
        $sql = "SELECT w.*,u.nick,u.mobile,u.avatar FROM ".$obj->table()." w LEFT JOIN  tbl_user u ON w.uid=u.uid WHERE w.schoolId=".intval($schoolAdmin->schoolId)." ORDER BY ".$obj->key()." DESC ";
        $all = $obj->query($sql);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }

        $this->j(0,"",$all);
    }


    //学过的人列表
    public function learnedListAction(){
        $uid = mylogin::getUid(true);

        $id = r_int("schoolId");
        $this->j(0,'',$this->getSchoolLearned($id));
    }

    private function getSchoolLearned($schoolId){
        $obj = new SchoolLearned();
        $sql = "SELECT * FROM ".$obj->table()." WHERE  schoolId=".$schoolId;
        if(r('isDebug')){
            $sql = "SELECT * FROM ".$obj->table()." LIMIT 3";
        }

        $all = $obj->query($sql);
        $i =0;
        foreach($all as $item){
            if(!preg_match("/^http/i",$item['avatar'])){
                $all[$i]['avatar']  = FRONT_URL.$item['avatar'];
            }
            $i++;
        }
        return $all;
    }

    //学过
    public function learnedAction(){
        $uid = mylogin::getUid(true);
        $school = new School();
        $objId = r_int($school->key());
        $find = $school->find($objId);
        if(!$find) $this->j(-1,"参数错误",[$school->key()=>$objId]);

        $obj = new SchoolLearned();
        $obj->uid = $uid;
        $obj->schoolId= $objId;
        $find = $obj->find();
        if($find){//cancel
            /*$sql = "DELETE FROM ".$obj->table()." WHERE uid=$uid AND schoolId=$objId";
            $obj->query($sql);
            $school->learned = $school->learned-1;
            $school->save();*/
        }
        $user = new User();
        $user->find($uid);
        if($user->avatar){
            $obj->avatar = $user->avatar;
        }else{
            $obj->avatar = "/default.png";
        }
        if($user->nick){
            $obj->nick = $user->nick;
        }else{
            $obj->nick = "匿名";
        }

        $obj->save();
        $school->learned = $school->learned+1;
        $school->save();

        $this->j(0,"",['learned'=>$school->learned]);
    }

    public function focusAction(){
        $uid = mylogin::getUid(true);
        $schoolFeed = new SchoolFeed();
        $schoolFeed->load();
        $schoolFeed->uid = $uid;
        $find = $schoolFeed->find();
        if(!$find){
            $schoolFeed->save();//增加
            $schoolId = $schoolFeed->schoolId;

            $this->updateFeedCount($uid,$schoolFeed);
            $this->j(0,"关注成功",['schoolId'=>$schoolId,'action'=>'focus']);
        }else{
            $sql = "DELETE FROM ".$schoolFeed->table()." WHERE ".$schoolFeed->getConByLoad();
            $schoolFeed->query($sql);
            $schoolId = $schoolFeed->schoolId;

            $this->updateFeedCount($uid,$schoolFeed);
            $this->j(0,"取消关注成功",['schoolId'=>$schoolId,'action'=>'cancel']);
        }



    }

    private function updateFeedCount($uid,$schoolFeed){
        $sql = "SELECT COUNT(1) AS NUM FROM ".$schoolFeed->table()." WHERE uid=".$uid;
        $one = $schoolFeed->one($sql);
        $count = $one['NUM'];

        $user = new User();
        $user->find($uid);
        $user->focusCount = $count;
        $user->save();
    }

}



